﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using FlickrNet;
using Subgurim.Controles;

public partial class UI_TrailPhotos : System.Web.UI.Page
{
    public int TrailID
    {
        set
        {
            Session["TrailID"] = value;
        }
        get 
        {
            if (Session["TrailID"] == null)
            {
                Session["TrailID"] = "0";
            }
            return int.Parse(Session["TrailID"].ToString());
        }

    }

    protected int WaypointId
    {
        get 
        {
            int wpid = 0;
            int.TryParse(ddlWaypoins.SelectedItem.Value, out wpid);
            return wpid; 
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack && AppUser.currUser() == 0)
        {
            Response.Redirect("../Login.aspx");
        }

        if (!Page.IsPostBack && Request["TrailID"]!= null)
        {
            TrailID = int.Parse(Request["TrailID"]);
            /*
            if (!(BL_Trail.IsUserOwnedTrail(TrailID, AppUser.currUser()) || BL_Trail.IsPermitted(TrailID, AppUser.currUser())))
            {
                fu.Enabled = false;
                btnFlickr.Visible = false;
                btnRefresh.Visible = false;
                return;             
            }
            */
            hlBack.NavigateUrl += "?TrailID=" + this.TrailID.ToString();
            //RefreshPhotos();
            DataBind();
        }

        if (!Page.IsPostBack && Request.QueryString["frob"] != null)
        {
            FlickrImport();
        }

        if (fu.IsPosting)
            this.managePost();
        
    }

    public override void DataBind()
    {
        Bintje.Trail trail = Bintje.Trail.Get(this.TrailID);
        if (null != trail && null != trail.Waypoints && trail.Waypoints.Count > 0)
        {
            IList<string> imgsUrl = new List<String>();
            for (int i = 0; i < trail.Waypoints.Count; i++)
            {
                if (null != trail.Waypoints[i].ImageUrl && trail.Waypoints[i].ImageUrl.Length > 0)
                {
                    for (int j = 0; i < trail.Waypoints[i].ImageUrl.Length; j++)
                    {
                        imgsUrl.Add(trail.Waypoints[i].ImageUrl[j]);
                    }
                }
            }
            var pics = (from i in imgsUrl
                        select new {Url = i}).ToArray();
            if (null != pics)
            {
                dlImages.DataSource = pics;
                dlImages.DataBind();
            }

            var wp = (from w in trail.Waypoints
                      orderby w.Id
                      select new { Id = w.Id, Name = w.Name }).ToArray();
            if (null != wp)
            {
                ddlWaypoins.DataSource = wp;
                ddlWaypoins.DataTextField = "Name";
                ddlWaypoins.DataValueField = "Id";
                ddlWaypoins.DataBind();
            }
        }
        base.DataBind();
    }

    private void FlickrImport()
    {
        string frob = Request.QueryString["frob"];

        FlickrNet.Flickr flickr = new FlickrNet.Flickr();
        flickr.ApiKey = ConfigurationManager.AppSettings["FlickrApiKey"];
        flickr.ApiSecret = ConfigurationManager.AppSettings["FlickrApiSecret"];
        FlickrNet.Auth auth = null;
        try
        {
            auth = flickr.AuthGetToken(frob);
        }
        catch (Exception ex)
        {
            AuthenticateFlicker();
        }


        Session["AUTH_TOKEN"] = auth.Token;
        Session["USER_ID"] = auth.User.UserId;
        Session["USER_NAME"] = auth.User.Username;

        //Label1.Text = Session["USER_NAME"] + " successfully authenticated";

        FlickrNet.PhotoSearchOptions options = new FlickrNet.PhotoSearchOptions();
        options.UserId = Session["USER_ID"].ToString();// ConfigurationManager.AppSettings.Get("UserId");
        options.PerPage = 100;
        options.Page = 1;
        options.SortOrder = FlickrNet.PhotoSearchSortOrder.DatePostedDesc;

        FlickrNet.Photos photos = flickr.PhotosSearch(options);

        if (photos.PhotoCollection != null)
            AddFlickrPhotos(photos.PhotoCollection);

        
    }
    private void AddFlickrPhotos(Photo[] PhotoCollection)
    {
        foreach (Photo pic in PhotoCollection)
        {
            string imageURL = pic.LargeUrl;
            System.Net.WebClient client = new System.Net.WebClient();
            string filename = Util.RandomString() + System.IO.Path.GetExtension(imageURL);
            client.DownloadFile(imageURL, Server.MapPath( "~/upload/trail/") + filename);
            Util.SaveTNShotImage(360, 360, Server.MapPath("~/Upload/Trail/" + filename), "~/Upload/Trail", filename);              
            //BL_Trail.AddPhoto(TrailID, false, filename);
            AddImage(filename);
        }
        //Response.Redirect("TrailPhotos.aspx?TrailID=" + TrailID.ToString());
        dlImages.DataBind();
    }
    private void managePost()
    {
        HttpPostedFileAJAX pf = fu.PostedFile;
        if (pf.ContentType.Equals("image/gif") ||
            pf.ContentType.Equals("image/jpg") ||
            pf.ContentType.Equals("image/jpeg") ||
            pf.ContentType.Equals("image/png") ||
            pf.ContentType.Equals("image/bmp"))
        {
            if (pf.ContentLength <= 10 * 1024 * 1024)
            {
                string Filename = Util.RandomString() + System.IO.Path.GetExtension(pf.FileName);
                fu.SaveAs("~/Upload/Trail/", Filename);
                //BL_Trail.AddPhoto(TrailID, false, Filename);
                Util.SaveTNShotImage(360, 360, Server.MapPath("~/Upload/Trail/" + Filename), "~/Upload/Trail", Filename);

                AddImage(Filename);
            }
        }   
    }

    private void AddImage(string Filename)
    {
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Server.MapPath(string.Concat("~/Upload/Trail/", Filename)));
        System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
        Bintje.Image img = new Bintje.Image();
        img.FileName = Filename;
        img.ImageData = (byte[])converter.ConvertTo(bmp, typeof(byte[]));

        Bintje.Trail trail = Bintje.Trail.Get(this.TrailID);
        trail = trail.KeepImages(trail);
        if (null != trail && null != trail.Waypoints && trail.Waypoints.Count > 0)
        {
            Bintje.WayPoint waypoint = trail.Waypoints.First(w => w.Id == this.WaypointId);
            if (null != waypoint)
            {
                if (waypoint.Images == null)
                    waypoint.Images = new List<Bintje.Image>();
                waypoint.Images.Add(img);
                trail.Waypoints[trail.Waypoints.IndexOf(waypoint)] = waypoint;
                trail.Update();
            }
        }
    }

    /*
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        RefreshPhotos();
        Response.Redirect("TrailPhotos.aspx?TrailID=" + TrailID.ToString());
    }
    
    private void RefreshPhotos()
    {
        List<TrailImage> lstImages = BL_Trail.GetAllPhotos(TrailID);
        for (int i = 0; i < lstImages.Count; i++)
        {
            FileInfo FI = new FileInfo(Server.MapPath("~/Upload/Trail/" + lstImages[i].ImageName));
            if (!FI.Exists)
            {
                BL_Trail.DeletePhoto(lstImages[i].ImageName);
                FI.Delete();
                FileInfo FItn = new FileInfo(Server.MapPath("~/Upload/Trail/tn/" + lstImages[i].ImageName));
                if (FItn.Exists)
                {
                    FItn.Delete();
                }
            }
        }
    }
    */

    protected void btnFlickr_Click(object sender, EventArgs e)
    {
        AuthenticateFlicker();
    }
    private void AuthenticateFlicker()
    {
        FlickrNet.Flickr flickr = new FlickrNet.Flickr();

        // Want to request "read" access so call the AuthCalcWebUrl method.
        flickr.ApiKey = ConfigurationManager.AppSettings["FlickrApiKey"];
        flickr.ApiSecret = ConfigurationManager.AppSettings["FlickrApiSecret"];

        string auth_url = flickr.AuthCalcWebUrl(AuthLevel.Read);

        // Redirect to that URL

        Response.Redirect(auth_url);
    }
    
    protected void dlImages_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            /*
            Image img = (Image)e.Item.FindControl("img");
            string image = img.ImageUrl.Substring(img.ImageUrl.LastIndexOf('/') + 1);
            BL_Trail.DeletePhoto(image);
            string path = Server.MapPath("../Upload/Trail/" + image);
            FileInfo FI = new FileInfo(path);
            if (FI.Exists)
            {
                FI.Delete();
                path = Server.MapPath("../Upload/Trail/" + image);
                FileInfo FItn = new FileInfo(path);
                if (FItn.Exists)
                {
                    FItn.Delete();
                }
            }
            */

            HiddenField hfWpID = (HiddenField)e.Item.FindControl("hfWpID");
            if (null != hfWpID)
            {
                int WpId = 0;
                int.TryParse(hfWpID.Value, out WpId);
                if (WpId > 0)
                {
                    Bintje.Trail trail = Bintje.Trail.Get(this.TrailID);
                    if (null != trail && null != trail.Waypoints && trail.Waypoints.Count > 0)
                    {
                        trail = trail.KeepImages(trail);
                        Bintje.WayPoint waypoint = trail.Waypoints.First(w => w.Id == WpId);
                        if (null != waypoint)
                        {
                            if (null != waypoint.Images)
                            {
                                Bintje.Image img = waypoint.Images.First(i => i.Id == int.Parse(e.CommandArgument.ToString()));
                                if (null != img)
                                {
                                    waypoint.Images.Remove(img);
                                    trail.Waypoints[trail.Waypoints.IndexOf(waypoint)] = waypoint;
                                    trail.Update();
                                    dlImages.DataBind();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
